package jfundertow.websocket;

import com.jfinal.server.undertow.UndertowConfig;
import com.jfinal.server.undertow.UndertowServer;
import io.undertow.server.HttpHandler;
import io.undertow.server.handlers.PathHandler;
import io.undertow.websockets.WebSocketConnectionCallback;
import io.undertow.websockets.core.AbstractReceiveListener;
import io.undertow.websockets.core.BufferedTextMessage;
import io.undertow.websockets.core.WebSocketChannel;
import io.undertow.websockets.core.WebSockets;
import io.undertow.websockets.spi.WebSocketHttpExchange;

import static io.undertow.Handlers.path;
import static io.undertow.Handlers.websocket;

public class MyServer extends UndertowServer {
    protected MyServer(UndertowConfig undertowConfig) {
        super(undertowConfig);
    }

    @Override
    protected HttpHandler configHandler(HttpHandler next) {
        PathHandler pathHandler = (PathHandler) next;

        pathHandler.addPrefixPath("ws", websocket(new WebSocketConnectionCallback() {

            @Override
            public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
                channel.getReceiveSetter().set(new AbstractReceiveListener() {

                    /**
                     *  自行重写onError, onBinary
                     *
                     * @author 张天笑
                     * @time 2018/12/25 15:17
                     *
                     */


                    @Override
                    protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) {
                        final String messageData = message.getData();
                        for (WebSocketChannel session : channel.getPeerConnections()) {
                            WebSockets.sendText(messageData, session, null);
                        }
                    }
                });
                channel.resumeReceives();
            }

        }));

        return next;
    }
}
